import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:get/get.dart';
import 'package:flutter_base/config/app_routes.dart';

import 'package:flutter_base/user/model/app_user_info_model.dart';

import 'package:flutter_base/utils/shared/shared_key.dart';
import 'package:flutter_base/utils/shared/shared_storage.dart';

import '../http/http_export.dart';

/// 记录登录后用户信息
///
class AppUserManager {
  static final AppUserManager _instance = AppUserManager._();

  factory AppUserManager() => _instance;

  AppUserManager._() {
    // 超过30天需要重新登录
    // int? loginTime = SharedStorage().prefs.getInt(SharedKey.loginTime);
    // if (loginTime != null) {
    //   int time = DateTime.now()
    //       .subtract(const Duration(days: 30))
    //       .millisecondsSinceEpoch;
    //   if (time > loginTime) {
    //     return;
    //   }
    // }

    token = SharedStorage().prefs.getString(SharedKey.token) ?? "";
    String? info = SharedStorage().prefs.getString(SharedKey.userInfo);
    if (info != null) {
      user.value = AppUserInfoModel.fromJson(json.decode(info.toBase64Decode));
      refreshUserInfo();
    }
  }

  Rxn<AppUserInfoModel> user = Rxn();

  String token = "";

  int? get uid => user.value?.uid;

  void remove() {
    token = "";
    user.value = null;

    SharedStorage().prefs.remove(SharedKey.token);
    SharedStorage().prefs.remove(SharedKey.userInfo);
    SharedStorage().prefs.remove(SharedKey.loginTime);
  }

  // 判断用户是否已登录
  bool get isLogin => token.isNotEmpty && (user.value?.uid ?? 0) > 0;

  Future<bool> refreshUserInfo() async {
    var res = await HttpManager().get<AppUserInfoModel>(
      API.userInfo,
      fromJson: AppUserInfoModel.fromJson,
    );
    if (res.isSuccess) {
      updateUserInfo(res.data);
    }
    return res.isSuccess;
  }

  //0退出即可，1异地登录，登录过期，2账号禁用
  Future<void> logout() async {
    // if (Get.currentRoute == AppRoutes.login ) {
    //   return;
    // }
    remove();

    // bool walletShow = true;
    token = "";
    user.value = null;

    Get.offAllNamed(AppRoutes.login);

  }

  void updateUserInfo(AppUserInfoModel userInfo) {
    user.value = userInfo;
    SharedStorage()
        .prefs
        .setString(SharedKey.userInfo, json.encode(userInfo).toBase64Encode);
  }

  Future<bool> updateToken(String? t) async {
    if (t != null) {
      token = t;
      bool isSuccess = await refreshUserInfo();
      if (isSuccess == true) {
        SharedStorage().prefs.setString(SharedKey.token, t);
        SharedStorage()
            .prefs
            .setInt(SharedKey.loginTime, DateTime.now().millisecondsSinceEpoch);
      }
      return isSuccess;
    }
    return false;
  }

  // 更新用户信息
  static Future<HttpResponse> updateUserInfoToServer({
    String? avatar,
    String? username,
    String? birthday,
    ///0未知 1男 2女
    int? sex,
    // int? acceptNotice,
    // int? shakeOpen,
    // int? soundOpen,
    // int? isInit,
    // String? payPassword,
    // int? callStatus,
    // // List<ModelHomeSingleChatCallResource>? resources,
    // int? callDiamond,
    bool showLoading = false,
    // String? realName,
    //
    // String? idCard,
    // bool? openOrderNotice,
    // bool? openMsgNotice,
    // bool? isOffline,
    // String? sign,
    // String? sound,
    // int? soundTime,
    // int? orderTime,
    // int? orderTotalPrice,
    // String? gameIds,
    // int? gameOrderStatus,
    // int? emotion,
    // int? job,
    // bool? giftEffect,
    // bool? mountEffect,
    // bool? joinHide,
    // bool? rankHide,
    // int? city,
  }) async {
    var params = <String, dynamic>{};
    // if (nickname != null) {
    //   params['nickname'] = nickname;
    // }
    if (avatar != null) {
      params['avatar'] = avatar;
    }
    if (username != null) {
      params['username'] = username;
    }
    if (birthday != null) {
      params['birthday'] = birthday;
    }
    if (sex != null) {
      params['sex'] = sex;
    }
    // if (acceptNotice != null) {
    //   params['accept_notice'] = acceptNotice;
    // }
    // if (shakeOpen != null) {
    //   params['shake_open'] = shakeOpen;
    // }
    // if (soundOpen != null) {
    //   params['sound_open'] = soundOpen;
    // }
    // if (isInit != null) {
    //   params['is_init'] = isInit;
    // }
    // if (payPassword != null) {
    //   params['pay_password'] = payPassword;
    // }
    // if (callStatus != null) {
    //   params['call_status'] = callStatus;
    // }
    // if (callDiamond != null) {
    //   params['call_diamond'] = callDiamond;
    // }
    //
    // if (realName != null) {
    //   params['real_name'] = realName;
    // }
    //
    // if (idCard != null) {
    //   params['id_number'] = idCard;
    // }
    //
    // if (openOrderNotice != null) {
    //   params['order_msg_notice'] = openOrderNotice == true ? 1 : 2;
    // }
    // if (openMsgNotice != null) {
    //   params['msg_notice'] = openMsgNotice == true ? 1 : 2;
    // }
    //
    // if (isOffline != null) {
    //   params['is_offline'] = isOffline == true ? 1 : 2;
    // }
    // if (giftEffect != null) {
    //   params['gift_effect'] = giftEffect == true ? 1 : 2;
    // }
    // if (mountEffect != null) {
    //   params['mount_effect'] = mountEffect == true ? 1 : 2;
    // }
    // if (joinHide != null) {
    //   params['join_hide'] = joinHide == true ? 1 : 2;
    // }
    // if (rankHide != null) {
    //   params['rank_hide'] = rankHide == true ? 1 : 2;
    // }
    // if (sign != null) {
    //   params['sign'] = sign;
    // }
    // if (sound != null) {
    //   params['sound'] = sound;
    // }
    // if (soundTime != null) {
    //   params['sound_time'] = soundTime;
    // }
    // if (orderTime != null) {
    //   params['order_time'] = orderTime;
    // }
    // if (orderTotalPrice != null) {
    //   params['order_total_price'] = orderTotalPrice;
    // }
    // if (gameIds != null) {
    //   params['game_ids'] = gameIds;
    // }
    // if (gameOrderStatus != null) {
    //   params['game_order_status'] = gameOrderStatus;
    // }
    // if (emotion != null) {
    //   params['emotion'] = emotion;
    // }
    // if (job != null) {
    //   params['job_id'] = job;
    // }
    // if (city != null) {
    //   params['city_id'] = city;
    // }

    return await HttpManager().put(API.userInfo,
        params: params,
        uiType: showLoading ? HttpUIType.loadingAndToast : HttpUIType.none);
  }
}
